﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.Course;
using System.Collections.Generic;
using PowerCreator.LMS.Grade.Entity;
using PowerCreator.LMS.Web.Grade;
using PowerCreator.LMS.ASF2JPG;
using PowerCreator.LMS.ViewQuery;

public partial class sysadmin_CourseManager_EditResourceInfo : PowerCreator.LMS.Web.Base.BasePage
{
    Course opCourse = new Course();
    ViewQuery opView = new ViewQuery();
    PowerCreator.LMS.Course.Core.CourseResource opCr = new PowerCreator.LMS.Course.Core.CourseResource(); 
    //从课件content.xml文件中读取到的参数
    protected string _guid = "";
    protected DateTime _starttime = DateTime.MinValue;
    protected string _videotime = "";
    private ASF2JPG opAsf2Jpg = new ASF2JPG();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string courseresid = "0";
            courseresid = Request.QueryString["CourseresID"].ToString();
            ViewState["CourseresID"] = courseresid.ToString();
            InitPage();
            BinderCourseResourceType();
            BinderSysResourceType();

            BinderPage();
        }
    }
    protected override void InitPage()
    {
        lbl_InfoTitle_AddVirtual.Text = GetLanageValueByKey("lbl_EditResourceInfo_InfoTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_ResourceName.Text = GetLanageValueByKey("lbl_EditResourceInfo_ResourceName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_ResourceClass.Text = GetLanageValueByKey("lbl_EditResourceInfo_ResourceClass", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseName.Text = GetLanageValueByKey("lbl_EditResourceInfo_CourseName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_VideoTime.Text = GetLanageValueByKey("lbl_EditResourceInfo_VideoTime", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_AuthorName.Text = GetLanageValueByKey("lbl_EditResourceInfo_AuthorName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CoursersRestpID.Text = GetLanageValueByKey("lbl_EditResourceInfo_CoursersRestpID", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Remark.Text = GetLanageValueByKey("lbl_EditResourceInfo_Remark", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_advert.Text = GetLanageValueByKey("lbl_EditResourceInfo_advert", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_advert_English.Text = GetLanageValueByKey("lbl_EditResourceInfo_advert_English", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Url.Text = GetLanageValueByKey("lbl_EditResourceInfo_Url", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_advert_url.Text = GetLanageValueByKey("lbl_EditResourceInfo_advert_url", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_EntryFileName.Text = GetLanageValueByKey("lbl_EditResourceInfo_EntryFileName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_advert_htm.Text = GetLanageValueByKey("lbl_EditResourceInfo_advert_htm", PowerCreator.LMS.Language.LanagetItemType.Page);

        rfv_txt_ResourceName.ErrorMessage = GetLanageValueByKey("AddCourseInfo_msg_m1", PowerCreator.LMS.Language.LanagetItemType.Page);
        RequiredFieldValidator1.ErrorMessage = GetLanageValueByKey("AddResourceInfo_msg_m2", PowerCreator.LMS.Language.LanagetItemType.Page);
        RequiredFieldValidator2.ErrorMessage = GetLanageValueByKey("AddResourceInfo_msg_m3", PowerCreator.LMS.Language.LanagetItemType.Page);

        btnTest.Value = GetLanageValueByKey("btn_EditResourceInfo_Test", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnPreview.Text = GetLanageValueByKey("btn_EditResourceInfo_Preview", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_Save.Value = GetLanageValueByKey("btn_EditResourceInfo_Save", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_Reset.Text = GetLanageValueByKey("btn_EditResourceInfo_Reset", PowerCreator.LMS.Language.LanagetItemType.Page);
        base.InitPage();
    }
    private void BinderPage()
    {
        string crid = ViewState["CourseresID"].ToString();
        VOTCourseResource vo = opCourse.LoadCourseResource(int.Parse(crid));
        if (vo != null)
        {
            ViewState["CourseID"] = vo.FKCourseresCourseID.ToString();
            ViewState["ResourceID"] = vo.FKCoursersResourceID.ToString();
            ViewState["CourseResourceID"] = vo.CourseresID.ToString();

            VOTOCourse voCourse = opCourse.LoadVOTCourse(vo.FKCourseresCourseID);
            if (voCourse != null)
            {
                lab_CourseName.Text = voCourse.CourseName;
                lab_CourseName.ForeColor = System.Drawing.Color.Red;
            }
            if (vo.CoursersClass == Convert.ToInt16(CoursersClass.Courseware))
            {
                VOTResource voResource = opCourse.LoadResource(vo.FKCoursersResourceID);
                txt_AuthorName.Value = voResource.ResourceAuthor;
                txt_EntryFileName.Value = voResource.ResourceEntry;
                txt_ResourceName.Value = voResource.ResourceName;
                FreeTextBox1.Text = voResource.ResourceDescription;
                if (!voResource.ResourceUrl.StartsWith("/"))
                {
                    voResource.ResourceUrl = "/" + voResource.ResourceUrl;
                }
                if (!voResource.ResourceUrl.EndsWith("/"))
                {
                    voResource.ResourceUrl += "/";
                }
                txt_Url.Value = voResource.ResourceUrl;

                txt_VideoTime.Value = opCourse.GetTimeStr(voResource.ResourceVideoTime.ToString());
                ddl_ResourceClass.Items.FindByValue(voResource.ResourceClass.ToString()).Selected = true;
                ddl_ResourceClass.Enabled = false;
                if (vo.FKCoursersRestpID != null)
                {
                    if (vo.FKCoursersRestpID.ToString()!= "0")
                        ddl_CoursersRestpID.Items.FindByValue(vo.FKCoursersRestpID.ToString()).Selected = true;
                }

            }
            else if (vo.CoursersClass == Convert.ToInt16(CoursersClass.Paper))
            { 
                
            }
        }
    }
    private void BinderCourseResourceType()
    {
        string search = "";
        DataTable dt = opCourse.QueryResourceType(search);
        ddl_CoursersRestpID.DataSource = dt;
        ddl_CoursersRestpID.DataTextField = "RestpName";
        ddl_CoursersRestpID.DataValueField = "RestpID";
        ddl_CoursersRestpID.DataBind();
    }
    private void BinderSysResourceType()
    {
        List<SysResourceTypeItem> list = opCourse.GetSysResourceType();
        ddl_ResourceClass.DataSource = list;
        ddl_ResourceClass.DataTextField = "IdText";
        ddl_ResourceClass.DataValueField = "IdValue";
        ddl_ResourceClass.DataBind();
    }
    private bool CheckPageData()
    {
        string search = string.Format("ResourceName = '{0}' and ResourceID <> {1}", txt_ResourceName.Value, ViewState["ResourceID"]);
        if (opCourse.QueryResourceCount(search) != 0)
        {
            lbl_editresourceinfo_msg_resourcename.Text = "己经存在该资源名称，请重新输入!";
            return false;
        }
        return true;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        string url = "ResourceList.aspx?CourseID=" + ViewState["CourseID"].ToString();
        Script.RedirectURL(url);
    }
    protected void btnPreview_Click(object sender, EventArgs e)
    {
        string url = txt_Url.Value + txt_EntryFileName.Value;
        Script.NewOpenURL(WebUtils.WebRoot + url,"testfileurl");
    }
    protected void btn_Save_ServerClick(object sender, EventArgs e)
    {
        if (!CheckPageData()) return;
        VOTCourseResource voCR = opCr.LoadCourseResource(int.Parse(ViewState["CourseResourceID"].ToString()));
        VOTResource voResource = opCourse.LoadResource(int.Parse(ViewState["ResourceID"].ToString()));
        voResource.ResourceAuthor = txt_AuthorName.Value;
        voResource.ResourceClass = int.Parse(ddl_ResourceClass.SelectedValue.ToString());
        //voResource.ResourceClickNum = 0;
        voResource.ResourceDescription = FreeTextBox1.Text;
        voResource.ResourceEntry = txt_EntryFileName.Value;
        //voResource.ResourceIsRecommend = 0;
        voResource.ResourceLastVisitTime = DateTime.Now;
        voResource.ResourceMmsUpdateState = false;
        voResource.ResourceName = txt_ResourceName.Value;
        voResource.ResourceUrl = txt_Url.Value;
        voCR.FKCoursersRestpID = int.Parse(ddl_CoursersRestpID.SelectedValue.ToString());
        if (!voResource.ResourceUrl.StartsWith("/"))
        {
            voResource.ResourceUrl = "/" + voResource.ResourceUrl;
        }
        if (!voResource.ResourceUrl.EndsWith("/"))
        {
            voResource.ResourceUrl += "/";
        }

        voResource.ResourceVideoTime = opCourse.GetSecond(txt_VideoTime.Value.Trim());
        //voResource.ResourseState = 0;

        if (opCourse.UpdateResource(voResource))
        {
            //跟新课程资源表
            opCr.UpdateCourseResource(voCR);
            if (voResource.ResourceClass == 1)
            {
                //不在同一台服务器的话会有问题
                try
                {
                    //视频文件生成缩略图
                    string filePath = Server.MapPath(voResource.ResourceUrl);
                    opAsf2Jpg.LMSGetEveryJpg(filePath);
                }
                catch
                { }

                //评估模块相关修改  H:\課件虛擬目錄\course\0\CW20100723170304
                // ReadFile(HttpContext.Current.Server.MapPath(vo.ResourceUrl) + "\\"+"content.xml");
                    string xmlPath = HttpContext.Current.Server.MapPath(WebUtils.WebRoot + voResource.ResourceUrl + "\\" + "content.xml");
                    if (System.IO.File.Exists(xmlPath))
                    {
                        ReadFile(xmlPath);
                        //ReadFile("H:\\課件虛擬目錄\\course\\0\\CW20100723170304\\" + "content.xml");
                        if (_guid != null)
                            UpdateGradeResourceID(int.Parse(ViewState["ResourceID"].ToString()));
                        //如果设置为检查则根据content.xml中的时间修改记录
                        if (ConfigurationManager.AppSettings["CheckResourceVideoTime"].ToString() == "1")
                            UpdateResourceVideotime(int.Parse(ViewState["ResourceID"].ToString()));
                    }


            }
            else if (voResource.ResourceClass == 2)
            {
                //不在同一台服务器的话会有问题
                try
                {
                    //视频文件生成缩略图
                    string filePath = Server.MapPath(voResource.ResourceUrl);
                    opAsf2Jpg.LMSGetEveryJpg(filePath);
                }
                catch
                { }

            }


            string url = "ResourceList.aspx?CourseID=" + ViewState["CourseID"].ToString();
            Script.RedirectURL(url);
        }
    }
    protected void btnTest_ServerClick(object sender, EventArgs e)
    {
        string path = Server.MapPath(WebUtils.WebRoot + txt_Url.Value + txt_EntryFileName.Value);
        if (System.IO.File.Exists(path))
        {
            lbl_editorresource_msg_filepath.Text = "文件检查存在!";
        }
        else
        {
            lbl_editorresource_msg_filepath.Text = "文件不存在!路径：" + path;
        }
    }






    private void ReadFile(string filepath)
    {
        XmlTextReader reader = new XmlTextReader(filepath);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        XmlDocument xmlDoc = new XmlDocument();

        //将文件加载到XmlDocument对象中

        xmlDoc.Load(reader);

        //关闭连接

        reader.Close();


        XmlNode xnod = xmlDoc.DocumentElement;
        XmlNode xnodWorking;
        if (xnod.Name == "DOCUMENT")
        {
            //如果还有子节点，就递归地调用这个程序

            if (xnod.HasChildNodes)
            {
                xnodWorking = xnod.FirstChild;

                while (xnodWorking != null)
                {
                    if (xnodWorking.Name == "DATETIME")
                    {
                        string time = xnodWorking.FirstChild.Value;
                        _starttime = DateTime.Parse(time);
                    }
                    else if (xnodWorking.Name == "GUID")
                    {
                        _guid = xnodWorking.FirstChild.Value;
                    }
                    else if (xnodWorking.Name == "DURATION")
                    {
                        _videotime = xnodWorking.FirstChild.Value;
                    }

                    xnodWorking = xnodWorking.NextSibling;
                }

            }

        }

    }

    private void UpdateGradeResourceID(int ResourceID)
    {
        VOTGrade vo = new VOTGrade();
        GradeManager opGrade = new GradeManager();
        DataTable dt = new DataTable();
        string sql = "FKGradeContentGuid='" + _guid + "' ";
        dt = opGrade.QueryGrade(sql);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                vo.GradeID = int.Parse(dt.Rows[i]["GradeID"].ToString());
                vo.GradeScore = int.Parse(dt.Rows[i]["GradeScore"].ToString());
                vo.GradeContent = dt.Rows[i]["GradeContent"].ToString();
                vo.FKGradeSkillID = int.Parse(dt.Rows[i]["FKGradeSkillID"].ToString());
                vo.FKGradeContentGuid = dt.Rows[i]["FKGradeContentGuid"].ToString();
                vo.GradeCreatetime = DateTime.Parse(dt.Rows[i]["GradeCreatetime"].ToString());
                vo.FKGradeUserID = int.Parse(dt.Rows[i]["FKGradeUserID"].ToString());
                //修改FKGradeResourceID
                vo.FKGradeResourceID = ResourceID;
                //根据参数starttime即开始录课时间以及记录中的GradeCreatetime即记录产生时间计算出记录产生时视频的时间点，然后记录到数据表的GradeAsfTime字段中

                if (vo.GradeCreatetime != null)
                {
                    TimeSpan ts = PowerCreator.LMS.Common.Utils.TimeUtils.TimeCompart(_starttime, vo.GradeCreatetime);
                    vo.GradeAsfTime = int.Parse((ts.Ticks / 10000000).ToString());
                }
                opGrade.UpdateGrade(vo);
            }
        }
    }

    private void UpdateResourceVideotime(int ResourceID)
    {
        VOTResource vo = new VOTResource();
        string sql = "ResourceID=" + ResourceID;
        vo = opCourse.LoadResource(ResourceID);
        string[] str = _videotime.Split(':');
        int videotime = 0;
        if (str.Length == 3)
        {
            if (int.Parse(str[0]) > 0)
                videotime = int.Parse(str[0]) * 60;
            videotime = videotime + int.Parse(str[1]);
        }
        vo.ResourceVideoTime = videotime;
        opCourse.UpdateResource(vo);
    }

}
